<template>
  <div class="pageContent">
    <div class="centerAll">
      <Table
        ref="xrTable"
        :list-api="list"
        :status-api="status"
        :table-column="tableColumn"
        :page-config="pageConfig"
        :table-config="tableConfig"
        @openViewForm="openViewForm"
        @openEditForm="openEditForm">
        <template v-slot:addBtn>
          <el-button type="success" @click="openCreateForm()">新增</el-button>
        </template>
      </Table>
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="isRead ? '查看' : '新增'" width="860">
    <el-form :model="form" :rules="rules" ref="ruleFormRef" label-position="right" label-width="auto">
      <el-form-item label="加工方式名称：" prop="name">
        <span v-if="isRead">{{form.name}}</span>
        <el-input v-else v-model="form.name" autocomplete="off" maxlength="50" show-word-limit placeholder="请输入加工方式名称" />
      </el-form-item>
      <el-form-item label="对外展示名称：" prop="show_name">
        <span v-if="isRead">{{form.show_name}}</span>
        <el-input v-else v-model="form.show_name" autocomplete="off" maxlength="50" show-word-limit placeholder="请输入对外展示名称" />
      </el-form-item>
      <el-form-item label="关联药品类型：" prop="type_id">
        <span v-if="isRead">{{form.type_id}}</span>
        <el-select v-else v-model="form.type_id" clearable placeholder="请选择关联药品类型">
          <el-option v-for="(o, ok) in drugTypeOptions" :key="ok" :label="o.value" :value="o.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序优先级：" prop="sort">
        <span v-if="isRead">{{form.sort}}</span>
        <div class="priority" v-else>
          <el-input-number v-model="form.sort" :min="0" :max="10" controls-position="right" class="mx-4" placeholder="请输入排序优先级" />
        </div>
      </el-form-item>
      <el-form-item label="用法用量模板：" prop="use_limit_id" required>
        <span v-if="isRead">{{form.use_limit_id}}</span>
        <el-select v-else v-model="form.use_limit_id" clearable placeholder="请选择用法用量模板" @change="useLimitChange">
          <el-option v-for="(o, ok) in useLimitTemplateOptions" :key="ok" :label="o.value" :value="o.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="用法用量默认值：" prop="usage">
        <span v-if="isRead">{{form.usage}}</span>
        <div v-else class="usage">
          <span v-for="(u, uk) in useLimitArr" :key="uk">{{ u }}
            <el-input-number v-if="uk !== useLimitArr.length-1"
                             v-model="form.use_limit[uk]"
                             :controls="false"
                             controls-position="right"
                             class="mx-4" />
          </span>
        </div>
      </el-form-item>
      <el-form-item label="预计出药率" required>
        <el-col :span="7">
          <span v-if="isRead">{{form.rate_min}}</span>
          <el-form-item prop="rate_min">
            <el-input-number v-model="form.rate_min" controls-position="right" class="mx-4" placeholder="请输入" />%
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="7">
          <span v-if="isRead">{{form.rate_min}}</span>
          <el-form-item prop="rate_max">
            <el-input-number v-model="form.rate_max" controls-position="right" class="mx-4" placeholder="请输入" /> %
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="备注：">
        <span v-if="isRead">{{form.remark}}</span>
        <el-input v-else v-model="form.remark" autocomplete="off" maxlength="500" show-word-limit type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template v-if="!isRead" #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm()">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  // import {
  //   ElMessageBox
  // } from 'element-plus'
  import {
    ref,
    reactive,
    toRaw,
    onMounted, nextTick
  } from 'vue'
  import {list, status, useLimit} from "@/api/drug/drugProcess";
  import { search as drugTypeSearch } from "@/api/drug/drugType"
  import {pageConfig, tableColumn, tableConfig} from "./config";
  import Table from "@/components/Table/index.vue";
  import {create, update} from "@/api/drug/drugPack";

  // const dialogFormVisible = ref(true)
  const useLimitArr = ref([])
  const useLimitTemplateOptions = ref([])
  const drugTypeOptions = ref([])
  const isRead = ref(false)
  const form = reactive({
    use_limit_id: 1,
    use_limit: []
  })
  const ruleFormRef = ref()
  const queryFormRef = ref()
  const dialogFormVisible = ref(false)
  const rules = reactive({
    name: [{
      required: true,
      message: '请填写加工方式名称',
      trigger: 'blur'
    }],
    show_name: [{
      required: true,
      message: '请填写对外展示名称',
      trigger: 'blur'
    }],
    sort: [{
      required: true,
      message: '请填写对外展示名称',
      trigger: 'blur'
    }],
    type_id: [{
      required: true,
      message: '请选择关联药品类型',
      trigger: 'blur'
    }],
    rate_min: [{
      required: true,
      message: '请填写预计出药率',
      trigger: 'blur',
    }],
    rate_max: [{
      required: true,
      message: '请填写预计出药率',
      trigger: 'blur',
    }]
  });

  const openCreateForm = () => {
    isRead.value = false
    dialogFormVisible.value = true

    nextTick(() => {
      ruleFormRef.value.resetFields()
      ruleFormRef.value.clearValidate()
    })
  }

  const handleChange = (value) => {
    console.log(value)
  }

  const useLimitChange = (value) => {
    console.log(value)
    console.log(useLimitTemplateOptions.value)
    const useLimit = useLimitTemplateOptions.value.find(item=>item.id === value)
    useLimitArr.value = useLimit.value.split("X");
  }


  const getUseLimitTemplate = async() => {
    const res = await useLimit();
    useLimitTemplateOptions.value = res.data
  }

  const getDrugType = async() => {
    const res = await drugTypeSearch();
    drugTypeOptions.value = res.data
  }

  const submitForm = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const options = { ...form.value }
        if (options.use_limit) {
          options.use_limit = options.use_limit.join("_")
        }
        if (options.id) {
          await update(options)
        } else {
          await create(options)
        }
        dialogFormVisible.value = false
        xrTable.value.resetFormParent()
        await buildFormSelData();
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  onMounted(async() => {
    await getUseLimitTemplate()
    try {
      await getDrugType()
    } catch (e) {
      console.log(e)
    }
    useLimitChange(form.use_limit_id);
  })
</script>

<style lang="scss" scoped>
  .el-form-item {
    margin-right: 12px;
  }

  .custom-card {
    width: 100%;
  }

  .buttonAll {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }

  .usage ::v-deep .el-input-number {
    margin: 0 8px;
    width: 60px;
  }
  .priority ::v-deep .el-input__inner{
    text-align: left;
  }

  .rate ::v-deep .el-input-number {
    margin: 0 8px 0 0;
    width: 120px;
  }

  .priority {
    width: 100%;
  }

  .priority ::v-deep .el-input-number {
    width: 100%;
  }

  .el-card {
    box-shadow: none;
  }

  .table-container {
    overflow-x: auto;
  }

  .upload-demo {
    display: flex;

    >* {
      position: relative;
      flex: 1;
      padding: 5px 20px;
      margin: 10px;
      background-color: white;
    }
  }

  .demo-pagination-block {
    margin: 20px 0;
    display: flex;
    justify-content: center;
  }

  .demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
  }

  .demo-pagination-block .demonstration {
    margin-bottom: 16px;
  }

  @media screen and (max-width: $sm-width) {
    .upload-demo {
      flex-direction: column;
    }
  }
</style>
